package com.hectopascal.goalance.repository;

import com.hectopascal.goalance.pojo.Target;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Repository
public interface TargetRepository extends CrudRepository<Target, Integer> {

    @Query(value = "SELECT tar.*,u.username" +
            " FROM target tar" +
            " LEFT JOIN user u ON tar.user_id = u.id" +
            " WHERE (:userId IS NULL OR user_id = :userId)", nativeQuery = true)
    Optional<List<Target>> findTargerById(@Param("userId") Integer userId);

    //动态SQL更新Target
    @Modifying
    @Transactional
    @Query(value = "UPDATE target SET " +
            "name = CASE WHEN :name IS NOT NULL THEN :name ELSE name END, " +
            "description = CASE WHEN :description IS NOT NULL THEN :description ELSE description END, " +
            "progress = CASE WHEN :progress IS NOT NULL THEN :progress ELSE progress END, " +
            "deadline = CASE WHEN :deadline IS NOT NULL THEN :deadline ELSE deadline END " +
            "WHERE id = :id",
            nativeQuery =true)
    int updateTarget(String name, String description, Integer progress, Date deadline, Integer id);
    
}
